package org.dreamwork.jasmine2.engine;

import org.dreamwork.jasmine2.parser.*;
import org.dreamwork.util.StringUtil;

import javax.servlet.ServletContext;
import java.util.List;
import java.util.ArrayList;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.net.URL;
import java.net.URLConnection;
import java.io.*;

/**
 * Created by IntelliJ IDEA.
 * User: seth
 * Date: 2009-7-29
 * Time: 15:51:18
 */
public class PageScaner {
    private String uri;
    private boolean layoutSupported = false;

    private final Pattern pattern = Pattern.compile ("<%@\\s*taglib\\s+.*%>");
    private final Pattern page_pattern = Pattern.compile ("<%@\\s*page\\s+.*%>");
    private static final String LAYOUT_URI = "http://www.dreamwork.org/jasmine/ui/layout";

    public PageScaner (String uri) {
        this.uri = uri;
    }
      
    public List<TaglibDirective> scan () throws IOException {
        HttpContext current = HttpContext.current ();
        ServletContext context = current.getApplication ();
        String root = context.getRealPath ("/");
        String charset;
        Reader in;
        if (root == null) { // war
            URL url = getClass ().getResource (uri);
            URLConnection conn = url.openConnection ();
            charset = new CharsetDetector (url).getCharset ();
            in = new InputStreamReader (conn.getInputStream (), charset);
        } else {
            File jsp = new File (context.getRealPath (uri));
            charset = new CharsetDetector (jsp.toURI().toURL ()).getCharset ();
            in = new InputStreamReader (new FileInputStream (jsp), charset);
        }

        return scan (in);
    }

    private List<TaglibDirective> scan (Reader reader) throws IOException {
        char[] buff = new char [1024];
        int length;
        StringBuffer sb = new StringBuffer ();
        while ((length = reader.read (buff)) != -1) {
            sb.append (buff, 0, length);
        }
        reader.close ();

        Matcher m = pattern.matcher (sb);
        List<TaglibDirective> list = new ArrayList<TaglibDirective> ();
        while (m.find ()) {
            String group = m.group (0);
            TaglibDirective taglib = (TaglibDirective) JspDirective.getDirective (group);
            taglib.parse ();
            if (taglib.getName () != null)
                list.add (taglib);
        }

        m = page_pattern.matcher (sb);
        while (m.find ()) {
            String group = m.group (0);
            PageDirective taglib = (PageDirective) JspDirective.getDirective (group);
            try {
                taglib.parse ();
                if (!StringUtil.isEmpty (taglib.getAttribute ("layout")))
                    this.layoutSupported = true;
            } catch (ParseException pe) {
                throw new IOException (pe);
            }
        }

        return list;
    }

    public boolean isLayoutSupported () {
        return layoutSupported;
    }
}